package com.self.cloudmall.search.config;

import com.google.common.collect.Lists;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @version v1.0
 * @ClassName: ElasticConfig
 * @Description:
 */
@Configuration
public class ElasticConfig {

    @Value("${elasticsearch.nodes}")
    private String esNodes;

    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }

    @Bean
    public RestHighLevelClient elasticClient(){
        String[] nodes = esNodes.split(",");
        HttpHost[] hostList = new HttpHost[nodes.length];
        for (int i = 0; i < nodes.length; i++){
            String[] split = nodes[i].split(":");
            hostList[i]=new HttpHost(split[1].replace("//",""),Integer.parseInt(split[2].replace("/","")),split[0]);
        }
        RestClientBuilder restClientBuilder = RestClient.builder(hostList);
        return new RestHighLevelClient(restClientBuilder);
    }
}
